//
//  Strore_detailController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/11.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//
#define kWindowWidth                        ([[UIScreen mainScreen] bounds].size.width)
#define kWindowHeight   ([[UIScreen mainScreen] bounds].size.height)


#import "Strore_detailController.h"
//vendor
#import "RDVTabBarController.h"
//untils
#import "AppDelegate.h"
#import "ManagerGlobeUntil.h"
#import "Global.h"
#import "UIColor+Hex.h"
#import "UIImage+ColorToImage.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
#import "XiaoQuAndStoreInfoModel.h"
#import "FMDBManager.h"
//view
#import "Strore_detailView.h"
#import "Strore_detail_ContentCell.h"
#import "StroreRebateAndRecommendCell.h"
#import "ServerDetailPriceIntroducedCell.h"

//model
#import "Strore_detail_ContentModel.h"

//viewModel
#import "StoreGoodsDetailViewModel.h"
//controller
#import "HYBLoopScrollView.h"
#import "Login_Controller.h"
#import "MemberAwardController.h"
//vendor
#import "MTA.h"
#import "MJRefresh.h"

#define kbottomViewHight 49
@interface Strore_detailController ()<UITableViewDelegate,UITableViewDataSource,Strore_detailViewDelegate,UIWebViewDelegate> {
   
}

@property(strong,nonatomic)UITableView *tableView;
@property(nonatomic, strong)UIView *tableFooterView;
@property(nonatomic, strong)UIScrollView *rootScrollView;
@property(nonatomic, strong)UIWebView *image_textView;//图文详情
@property(nonatomic, strong)Strore_detailView *bottomView;//视图底部视图（加入购物车）
@property(nonatomic, assign)BOOL isWebFinshLoaded;//web页面是否完成加载
@property(nonatomic, strong)StoreGoodsDetailViewModel *viewModel;

//加入购物车栏
@property(weak,nonatomic)UIView *shopCarView;

@property(nonatomic,strong)NSMutableArray *dataSource;//产品名字 、描述 、价格

@property(nonatomic,strong)UILabel *productDetail;
//轮播图
@property(nonatomic,strong)NSMutableArray *images;
@property(nonatomic,strong)NSMutableArray *defaultImages;
@property(nonatomic, strong)HYBLoopScrollView *loopScrollView;
@end

@implementation Strore_detailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    self.title=@"商品详情";
    [self addBackNavItem];
     _dataSource = [[NSMutableArray alloc]init];
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        //请求商品详情数据
        [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                                  inView:self.view];
        [self.viewModel requestGoodsDetailDataWithGoodsId:self.goodsID isSelf:self.isSelf  success:^(NSArray *responseObjects) {
            [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
            [self.dataSource addObjectsFromArray:responseObjects];
            [self setUpsubView];
             [self.bottomView setUpyuanbaio];
            [self showTextAndImageWithHasDescribeState:self.viewModel.isHadTextAndImageDescribe];
        } failure:^(NSString *failureMessage) {
            [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
        }];
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:NO];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"详情页"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"详情页"];
}
#pragma mark -- request data
- (void)loadTextAndImageData {
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    NSString *adapterStr = @"";
    adapterStr = @"goods/detailDescribe";
    [parameter setObject:self.goodsID.length == 0 ? @"" : self.goodsID forKey:@"GOODSID"];
    [parameter setObject:model.storeID forKey:@"STOREID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:adapterStr success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                NSString *htmlContext = [NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"CONTEXT"]];
                if (htmlContext.length != 0) {
                    [weakSelf.image_textView loadHTMLString:htmlContext  baseURL:nil];
                }
                
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
        
        
    } failure:^(bool isFailure) {
        
        
    }];
}
#pragma mark -- UITableViewDataSource
//cell的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return [[self.dataSource objectAtIndex:section] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.dataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSDictionary *dataDic = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if(indexPath.section == 0 ){
        if (indexPath.row == 0) {//商品详情信息
            static NSString *goodsInfoIdentifier=@"goodsInfoIdentifier";
            Strore_detail_ContentCell *goodsInfoCell=[tableView dequeueReusableCellWithIdentifier:goodsInfoIdentifier];
            if(!goodsInfoCell) {
                goodsInfoCell=[[Strore_detail_ContentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:goodsInfoIdentifier];
                goodsInfoCell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            }
            [goodsInfoCell updateViewWithData:dataDic];
            return goodsInfoCell;
        } else {//返现或推荐
            static NSString *goodsRebateOrRecommendIdentifier=@"goodsRebateOrRecommendIdentifier";
            StroreRebateAndRecommendCell *rebateOrRecommendCell=[tableView dequeueReusableCellWithIdentifier:goodsRebateOrRecommendIdentifier];
            if(!rebateOrRecommendCell) {
                rebateOrRecommendCell=[[StroreRebateAndRecommendCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:goodsRebateOrRecommendIdentifier];
                rebateOrRecommendCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
            }
            [rebateOrRecommendCell updateViewWithData:dataDic];
            return rebateOrRecommendCell;
        }
    }
       //商品规格
        static NSString *identfy = @"guige";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identfy];
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identfy];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell.layer setBorderColor:[UIColor colorWithHexString:@"#c6c6c6"].CGColor];
        [cell.layer setBorderWidth:0.5];
        cell.textLabel.font = [UIFont systemFontOfSize:FontSize(15)];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#555555"];
        cell.textLabel.text = [NSString stringWithFormat:@"规格：%@",[dataDic objectForKey:@"guige"]];
        return cell;

}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {//商品详情信息
            Strore_detail_ContentCell *cell = (Strore_detail_ContentCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
            return [cell cellFactHight];
        } else  {//返现或推荐
            StroreRebateAndRecommendCell *cell = (StroreRebateAndRecommendCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
            return [cell cellFactHight];
        }
    }else if (indexPath.section == 1) {//商品规格
        return HightScalar(47);
    }
    return 10;
}
//分区样式
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    } else {
        return self.viewModel.isHadTextAndImageDescribe ? 10 : 0;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 10)];
        view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
        return view;
    } else {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0)];
        view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
        return view;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 1) {
        [_tableView deselectRowAtIndexPath:indexPath animated:YES];
        MemberAwardController *memberAwardVC = [[MemberAwardController alloc]init];
        [self.navigationController pushViewController:memberAwardVC animated:YES];
    }
}
#pragma mark -- Strore_detailViewDelegate(宝贝详情底部视图)
-(void)selectedItemWithTag:(NSInteger)tag {
    //tag =O 收藏  tag =1 购物车  tag =2 加入购物车
    
    if(tag == 0) {//关注
        if ([ManagerGlobeUntil sharedManager].transactionLogin) {
            if (self.viewModel.isCollectedGoods) {//取消关注
                [self.viewModel cancelMarkGoodsWithGoodsId:self.goodsID
                                                   success:^(NSString *successMsg) {
                                                       [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:successMsg inView:self.view];
                                                       NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                                                       Strore_detail_ContentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                                                       [cell updateMarkCount:self.viewModel.markCount];
                                                       self.bottomView.collectionBtn.selected = NO;
                                                   } failure:^(NSString *failureMessage) {
                                                       [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
                                                   }];
                
            } else {//添加关注
                [self.viewModel markGoodsWithGoodsId:self.goodsID isSelf:self.isSelf success:^(NSString *successMsg) {
                    [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:successMsg inView:self.view];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                    Strore_detail_ContentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                    [cell updateMarkCount:self.viewModel.markCount];
                    self.bottomView.collectionBtn.selected = YES;
                } failure:^(NSString *failureMessage) {
                    [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
                }];
            }
            
        } else {//未登陆
            Login_Controller *loginVC = [[Login_Controller alloc]init];
            loginVC.supperControllerType = kProductDetetailPushToLogin_ControllerSupperController;
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
            [self presentViewController:nav animated:YES completion:nil];
        }
        
    }else if(tag == 1){//跳转购物车
        
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        if (appDelegate.currentSelectedTabBarIndex == 3) {
            [self.navigationController popToRootViewControllerAnimated:NO];
        } else {
            [self.navigationController setViewControllers:@[[self.navigationController.childViewControllers firstObject]]];
            [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
            [appDelegate selectedControllerAtTabBarIndex:3];
        }
       
    }else {//加入购物车按钮
        [self.viewModel addGoodsToShopingCart];
  }

}
#pragma mark -- UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:webView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[ManagerGlobeUntil sharedManager] hideHUDFromeView:webView];
    NSString *scriptStr = [NSString stringWithFormat:@"var script = document.createElement('script');"
                           "script.type = 'text/javascript';"
                           "script.text = \"function ResizeImages() { "
                           "var myimg,oldwidth;"
                           "var maxwidth=%f;" //缩放系数
                           "for(i=0;i <document.images.length;i++){"
                           "myimg = document.images[i];"
                           "if(myimg.width > maxwidth){"
                           "oldwidth = myimg.width;"
                           "myimg.width = maxwidth;"
                           
                           "}"
                           "}"
                           "}\";"
                           "document.getElementsByTagName('head')[0].appendChild(script);",self.view.bounds.size.width - 2*8];
    [webView stringByEvaluatingJavaScriptFromString:scriptStr];
    
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    self.isWebFinshLoaded = YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
    self.isWebFinshLoaded = NO;
    [[ManagerGlobeUntil sharedManager] hideHUDFromeView:webView];
}

#pragma mark -- 刷新事件
- (void)footerRereshing {
    [UIView animateWithDuration:0.3 animations:^{
        self.rootScrollView.contentOffset = CGPointMake(0, self.rootScrollView.bounds.size.height);
    } completion:^(BOOL finished) {
        if (!self.isWebFinshLoaded) {
            [self loadTextAndImageData];
        }
        [self endRefreshing];
    }];
    
    
}
- (void)headerRefreshing {
    [UIView animateWithDuration:0.3 animations:^{
        self.rootScrollView.contentOffset = CGPointMake(0, 0);
    } completion:^(BOOL finished) {
        [self endHeaderRefreshing];
    }];
    
    
}
- (void)endRefreshing {
    [self.tableView footerEndRefreshing];
}

- (void)endHeaderRefreshing {
    [self.image_textView.scrollView headerEndRefreshing];
}

#pragma mark -- 是否展示图文详情
- (void)showTextAndImageWithHasDescribeState:(BOOL)isShow {
    //是否有图文介绍，1：有，0：没有
    if (!isShow) {
        self.tableFooterView.hidden = YES;
    } else {
        [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
        [self.tableView setFooterRemindMessageHidden:YES];
        [self.tableView setFooterArrowImageHide:YES];
    }
}
#pragma mark - 初始化控件
-(void)setUpsubView {
    [self.view addSubview:self.rootScrollView];
    [self.rootScrollView addSubview:self.tableView];
    [self.rootScrollView addSubview:self.image_textView];
    [self.view addSubview:self.bottomView];
    
}
#pragma mark -- setter Method
- (UIScrollView*)rootScrollView {
    if (!_rootScrollView) {
        CGRect frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)  - kbottomViewHight);
        UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:frame];
        scrollView.backgroundColor =  [UIColor clearColor];
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.scrollEnabled = NO;
        scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds), (CGRectGetHeight(self.view.bounds)  - kbottomViewHight)*2);
        _rootScrollView = scrollView;
    }
    return _rootScrollView;
}
- (UITableView*)tableView {
    if (!_tableView) {
        CGRect frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - kbottomViewHight);
        UITableView *tableview = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.backgroundColor = [UIColor clearColor];
        tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableview setTableFooterView:self.tableFooterView];
        [tableview setTableHeaderView:self.loopScrollView];
        _tableView = tableview;
    }
    return _tableView;
}
//table 头部视图
- (HYBLoopScrollView*)loopScrollView {
    if (!_loopScrollView) {
        CGRect loopScrollViewFrame = CGRectMake(0, 0, VIEW_WIDTH, VIEW_WIDTH);
        HYBLoopScrollView *loopView = [HYBLoopScrollView loopScrollViewWithFrame:loopScrollViewFrame
                                                           imageUrls:nil];
        
        loopView.delegate = (id<HYBLoopScrollViewDelegate>)self;
        //设置pagecontroll样式
        loopView.pageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:@"#c52720"];
        loopView.imageUrls = self.viewModel.goodsLoopImages;
        loopView.pageControl.pageIndicatorTintColor = [UIColor colorWithHexString:@"#dededd"];
        loopView.timeInterval = 5;//设置间隔时间
        loopView.placeholder = [UIImage imageNamed:@""];
        loopView.alignment = kPageControlAlignRight;//设置pagecontroll对齐方式
        _loopScrollView = loopView;
    }
    return _loopScrollView;
}

//table 底部视图
- (UIView*)tableFooterView {
    if (!_tableFooterView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 56)];
        [view setBackgroundColor:[UIColor whiteColor]];
        UIImage *sepLineImage = [UIImage imageNamed:@"gray_line"];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:sepLineImage];
        imageView.frame = CGRectMake(0, 0, VIEW_WIDTH, 0.5);
        [view addSubview:imageView];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"goodsDetailRefreshLogo"] forState:UIControlStateNormal];
        [button setTitle:@"上拉查看图文详情" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#555555"] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:FontSize(15)];
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        button.frame = CGRectMake(0,0.5, VIEW_WIDTH, 45);
        [view addSubview:button];
        _tableFooterView = view;
    }
    return _tableFooterView;
}

- (UIWebView*)image_textView {
    if (!_image_textView) {
        CGRect frame = CGRectMake(CGRectGetMinX(self.tableView.frame)
                                  , CGRectGetMaxY(self.tableView.frame)
                                  , CGRectGetWidth(self.tableView.bounds)
                                  , CGRectGetHeight(self.tableView.bounds));
        UIWebView *webView = [[UIWebView alloc]initWithFrame:frame];
        webView.delegate = self;
        webView.backgroundColor = [UIColor clearColor];
        [webView.scrollView addHeaderWithTarget:self action:@selector(headerRefreshing)];
        [webView.scrollView setHeaderPullToRefreshText:@"下拉回到商品详情"];
        [webView.scrollView setHeaderReleaseToRefreshText:@"释放回到商品详情"];
        [webView.scrollView setHeaderArrowImageHide:YES];
        [webView.scrollView setLastUpdateTimeLabel:YES];
        _image_textView = webView;
    }
    return _image_textView;
}
-(Strore_detailView*)bottomView {
    if (!_bottomView) {
        Strore_detailView *bottomview = [[Strore_detailView alloc]initWithFrame:CGRectMake(0
                                                                                           , CGRectGetHeight(self.view.bounds) - kbottomViewHight
                                                                                           ,CGRectGetWidth(self.tableView.bounds)
                                                                                           , kbottomViewHight)
                                                                     bottomType:kgoodDetailBottomType];
        bottomview.delegate = self;
        bottomview.goodImage = self.viewModel.goodsLogo;
        bottomview.collectionBtn.selected = self.viewModel.isCollectedGoods;
        _bottomView = bottomview;
    }
    return _bottomView;
}
- (StoreGoodsDetailViewModel*)viewModel {
    if (!_viewModel) {
        _viewModel = [[StoreGoodsDetailViewModel alloc]init];
    }
    return _viewModel;
}

-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
